package com.yi.wood.gob.gate;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by moyi on 2018/9/20 9:38
 *
 * @author moyi
 * websocket 服务启动入口
 */
@Service
public class GobGateSocket {

    private static Logger LOG = LoggerFactory.getLogger(GobGateSocket.class);

    /**
     * 服务监听端口
     */
    @Value("${wood.gob.socket.port}")
    private int port;

    @Resource
    private GobInitializer gobInitializer;

    /**
     * spring 容器加载完后执行，初始化 webSocket
     */
    public void init(){
        LOG.info("netty webSocket starting on port:{}",port);
        EventLoopGroup serverGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(serverGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(gobInitializer);
            LOG.info("netty webSocket started, ok!");
            Channel channel = bootstrap.bind(port).sync().channel();
            channel.closeFuture().sync();
        }catch (InterruptedException e){
            LOG.error("start webSocket error:{}",e.getMessage());
            serverGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            e.printStackTrace();
        }
    }
}
